package com.jl15988.simpletools.appcore.strategy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 本地存储策略实现
 *
 * @author jl15988
 */
@Slf4j
@Component("localStorageStrategy")
public class LocalStorageStrategy implements StorageStrategy {

    @Value("${file.storage.local-path}")
    private String localPath;

    @Override
    public String uploadFile(MultipartFile file, String path) {
        try {
            return uploadFile(file.getInputStream(), file.getOriginalFilename(), path);
        } catch (IOException e) {
            log.error("上传文件失败", e);
            throw new RuntimeException("上传文件失败", e);
        }
    }

    @Override
    public String uploadFile(InputStream inputStream, String fileName, String path) {
        try {
            // 创建目录
            String fullPath = localPath + File.separator + path;
            File directory = new File(fullPath);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    throw new RuntimeException("创建目录失败: " + fullPath);
                }
            }

            // 保存文件
            Path targetPath = Paths.get(fullPath, fileName);
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            return path + File.separator + fileName;
        } catch (IOException e) {
            log.error("上传文件失败", e);
            throw new RuntimeException("上传文件失败", e);
        }
    }

    @Override
    public boolean deleteFile(String path) {
        try {
            Path filePath = Paths.get(localPath, path);
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            log.error("删除文件失败", e);
            return false;
        }
    }

    @Override
    public String getFileUrl(String path) {
        return "/api/v1/file/" + path;
    }
} 